<script setup>
import topNav from "../../components/topNav.vue";
import { onMounted, reactive, ref, getCurrentInstance, computed } from "vue";
import { onLoad, onReachBottom, onShow } from "@dcloudio/uni-app";
// import { appProductQuery, productCount } from "@/services/goods";
// import { purchaseQuery } from "@/services/delivery";

import { appReceivePurchase, appReceive } from "@/services/send";
import { base_URL } from "@/utils/http";
import { operation } from "@/utils/num.js";

// import tabbarView from "../components/tabbar.vue";
const scrollTop = ref(0);
const code = ref("");
const id = ref("");

onLoad((option) => {
  // code.value = option.code ? option.code : "";
  // form.value.keyword = option.code ? option.code : "";
  id.value = option.id ? option.id : "";
  getappReceive();
});
onShow(() => {
  // getAppProductQuery(1);
});

const saveFun = () => {
  // console.log("取消");
  // form.value.name = "";
  // loading.value = "";
  // getAppProductQuery(1);
};

onReachBottom(() => {
  console.log("触底了");
  // getAppProductQuery();
});

//获取商品

const productData = ref({});
const getappReceive = async () => {
  try {
    let res = await appReceivePurchase({ id: id.value });
    if (res.code == 200) {
      res.data.products.forEach((item) => {
        item.purchaseOrderDetailId = item.id;
        console.log(item.orderNum, item.receiveNum);
        item.receiveNumtwo = operation(
          item.orderNum,
          item.receiveNum,

          2,
          "subtract"
        );
        item.inReceiveNum = "";
        item.checklist = [];
        item.description = "";
      });
      productData.value = res.data;
    } else {
    }

    console.log(res);
  } catch (e) {}
};

//编辑商品
const goEdt = (item) => {
  uni.navigateTo({ url: "/pages/delivery/det/index?id=" + item.id });
};

const scanFun = () => {
  console.log("扫码");
  // #ifdef H5
  uni.navigateTo({ url: "/pages/code_sand/index?type=goods" });
  // #endif
  // #ifdef APP-PLUS
  // 允许从相机和相册扫码
  const systemInfo = uni.getSystemInfoSync();
  if (systemInfo.osName === "android") {
    if (uni.getStorageSync("isspermission")) {
    } else {
      ishowcamera.value = true;
    }

    plus.android.requestPermissions(["android.permission.CAMERA"], (e) => {
      if (e.deniedAlways.length > 0) {
        // 弹出提示框解释为何需要权限，引导用户打开设置页面开启

        ishowcamera.value = false;
      } else if (e.deniedPresent.length > 0) {
        //权限被临时拒绝
        // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限
        ishowcamera.value = false;
      } else if (e.deniedAlways.length > 0) {
        //权限被永久拒绝
        // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限
        ishowcamera.value = false;
      } else {
        plus.android.requestPermissions(
          ["android.permission.READ_EXTERNAL_STORAGE"],
          (e) => {
            if (e.deniedAlways.length > 0) {
              // 弹出提示框解释为何需要权限，引导用户打开设置页面开启

              ishowcamera.value = false;
            } else if (e.deniedPresent.length > 0) {
              //权限被临时拒绝
              // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限

              ishowcamera.value = false;
            } else if (e.deniedAlways.length > 0) {
              //权限被永久拒绝
              // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限

              ishowcamera.value = false;
            } else {
              ishowcamera.value = false;
              uni.setStorageSync("isspermission", true);

              uni.scanCode({
                scanType: ["barCode", "qrCode"],
                autoDecodeCharset: true,
                success: function (res) {
                  console.log("条码类型：" + res.scanType);
                  console.log("条码内容：" + res.result);
                  form.value.keyword = res.result;
                  getAppProductQuery(1);
                },
              });
            }
          }
        );
      }
    });
    return;
  }
  uni.scanCode({
    scanType: ["barCode", "qrCode"],
    autoDecodeCharset: true,
    success: function (res) {
      console.log("条码类型：" + res.scanType);
      console.log("条码内容：" + res.result);
      form.value.keyword = res.result;
      getAppProductQuery(1);
    },
  });
  // #endif
};
const searchFun = () => {
  console.log("搜索");
  uni.navigateTo({
    url: "/pages/goods/goods_search/index",
  });
};
const goadd = async () => {
  if (isUpload.value) {
    return uni.showToast({
      title: "请等待上传完成",
      icon: "none",
    });
  }
  if (isUploadTwo.value) {
    return uni.showToast({
      title: "请等待上传完成",
      icon: "none",
    });
  }
  if (fileList.value.length <= 0) {
    return uni.showToast({
      title: "请上传签收单据",
      icon: "none",
    });
  }
  let isNum = false;
  let isNum2 = true;
  let products = [];
  productData.value.products.forEach((item) => {
    if (item.inReceiveNum > 0) {
      isNum = true;
      products.push({
        productId: item.productId,
        purchaseOrderDetailId: item.id,
        receiveNum: item.inReceiveNum,

        description: item.description,
        checklist: item.checklist.length > 0 ? item.checklist[0].url : "",
      });
    }
  });
  giftList.value.forEach((item) => {
    if (!item.inReceiveNum) {
      isNum2 = false;
    }
    if (item.inReceiveNum > 0) {
      products.push({
        productId: item.id,

        receiveNum: item.inReceiveNum,

        description: item.description ? item.description : "",
        checklist:
          item.checklist && item.checklist.length > 0
            ? item.checklist[0].url
            : "",
      });
    }
  });
  if (!isNum) {
    return uni.showToast({
      title: "请填写需要收货数量",
      icon: "none",
    });
  }
  if (!isNum2) {
    return uni.showToast({
      title: "请填写赠品需要收货数量",
      icon: "none",
    });
  }

  try {
    let res = await appReceive({
      purchaseOrderId: id.value,
      signDocument: fileList.value
        .map((res) => {
          return res.url;
        })
        .join(","),
      products: products,
      description: description.value,
    });
    if (res.code == 200) {
      uni.showToast({
        title: "提交成功",
        icon: "none",
        mask: true,
      });
      uni.redirectTo({
        url: "/pages/sends/list/index",
      });
    } else {
      uni.showToast({
        title: res.msg,
        icon: "none",
      });
    }
  } catch (e) {
    uni.showToast({
      title: e.msg,
      icon: "none",
    });
  }

  // uni.navigateTo({
  //   url: "/pages/goods/goods_add/index?type=add",
  // });
};

const searchlistfun = () => {};

const upper = (e) => {
  console.log(e);
};
const lower = (e) => {
  console.log(e);
};
const scroll = (e) => {
  console.log(e);
};
const sandfun = (item) => {
  uni.navigateTo({
    url: "/pages/delivery/send/index?id=" + item.id,
  });
};

const groupChange = (n) => {
  console.log("groupChange", n);
};

// 删除图片
const deletePic = (event) => {
  productData.value.products[selectReceiveIndex.value].checklist.splice(
    event.index,
    1
  );
};
// 新增图片
const isUpload = ref(false);
const afterRead = async (event) => {
  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
  let lists = [].concat(event.file);
  let fileListLen =
    productData.value.products[selectReceiveIndex.value].checklist.length;
  lists.map((item) => {
    productData.value.products[selectReceiveIndex.value].checklist.push({
      ...item,
      status: "uploading",
      message: "上传中",
    });
  });
  let Uploadnum = 0;

  console.log("12312312312", lists);
  for (let i = 0; i < lists.length; i++) {
    try {
      const result = await uploadFilePromise(lists[i].url);
      console.log(result);
      let item =
        productData.value.products[selectReceiveIndex.value].checklist[
          fileListLen
        ];
      productData.value.products[selectReceiveIndex.value].checklist.splice(
        fileListLen,
        1,
        {
          ...item,
          status: "success",
          message: "",
          url: result.data.url,
        }
      );
      fileListLen++;
      Uploadnum = Uploadnum + 1;
      if (Uploadnum == lists.length) {
        isUpload.value = false;
      }
    } catch (e) {
      Uploadnum = Uploadnum + 1;

      if (Uploadnum == lists.length) {
        isUpload.value = false;
      }
      productData.value.products[selectReceiveIndex.value].checklist.splice(
        i,
        1
      );
      uni.showToast({
        title: e.message,
        icon: "none",
      });
    }
  }
};

// 删除图片
const deletePicTwo = (event) => {
  fileList.value.splice(event.index, 1);
};
const isUploadTwo = ref(false);
// 新增图片
const afterReadTwo = async (event) => {
  isUploadTwo.value = true;
  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
  let lists = [].concat(event.file);
  let fileListLen = fileList.value.length;
  lists.map((item) => {
    fileList.value.push({
      ...item,
      status: "uploading",
      message: "上传中",
    });
  });
  let Uploadnum = 0;

  for (let i = 0; i < lists.length; i++) {
    try {
      const result = await uploadFilePromise(lists[i].url);

      let item = fileList.value[fileListLen];
      fileList.value.splice(fileListLen, 1, {
        ...item,
        status: "success",
        message: "",
        url: result.data.url,
      });
      Uploadnum = Uploadnum + 1;
      fileListLen++;
      if (Uploadnum == lists.length) {
        isUploadTwo.value = false;
      }
    } catch (e) {
      Uploadnum = Uploadnum + 1;
      if (Uploadnum == lists.length) {
        isUploadTwo.value = false;
      }
      fileList.value.splice(i, 1);
      uni.showToast({
        title: e.message,
        icon: "none",
      });
    }
  }
};

const uploadFilePromise = (url) => {
  return new Promise((resolve, reject) => {
    let a = uni.uploadFile({
      url: base_URL + "/app/product/image", // 仅为示例，非真实的接口地址
      filePath: url,
      header: {
        "X-Auth-Token": uni.getStorageSync("X-Auth-Token"),
      },
      name: "file",
      formData: {
        user: "test",
      },
      success: (res) => {
        console.log(res);
        let data = JSON.parse(res.data);
        if (data.code == 200) {
          setTimeout(() => {
            resolve(data);
          }, 1000);
        } else {
          reject(data);
        }
      },
    });
  });
};

const fileList = ref([]);
const description = ref("");
//选择收货单
const selectReceiveIndex = ref(-1);
const goReceive = (item, index) => {
  selectReceiveIndex.value = index;
};

const ishowcamera = ref(false);
const getQX = () => {
  // #ifdef APP-PLUS

  const systemInfo = uni.getSystemInfoSync();

  if (systemInfo.osName === "android") {
    if (uni.getStorageSync("isspermission")) {
      return;
    } else {
      ishowcamera.value = true;
    }

    plus.android.requestPermissions(["android.permission.CAMERA"], (e) => {
      if (e.deniedAlways.length > 0) {
        // 弹出提示框解释为何需要权限，引导用户打开设置页面开启

        ishowcamera.value = false;
      } else if (e.deniedPresent.length > 0) {
        //权限被临时拒绝
        // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限

        ishowcamera.value = false;
      } else if (e.deniedAlways.length > 0) {
        //权限被永久拒绝
        // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限

        ishowcamera.value = false;
      } else {
        console.log("22222222222");
        plus.android.requestPermissions(
          ["android.permission.READ_EXTERNAL_STORAGE"],
          (e) => {
            if (e.deniedAlways.length > 0) {
              // 弹出提示框解释为何需要权限，引导用户打开设置页面开启

              ishowcamera.value = false;
            } else if (e.deniedPresent.length > 0) {
              //权限被临时拒绝
              // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限

              ishowcamera.value = false;
            } else if (e.deniedAlways.length > 0) {
              //权限被永久拒绝
              // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限

              ishowcamera.value = false;
            } else {
              ishowcamera.value = false;
              uni.setStorageSync("isspermission", true);
            }
          }
        );
      }
    });
  }
  return;
  // #endif
};

//选择赠品

const selectFun = () => {
  uni.navigateTo({
    url: "/pages/sends/goods_search/index",
  });
};

const giftList = ref([]);

function getProduce(data) {
  giftList.value = [...giftList.value, ...data];
  console.log(giftList.value);
}

// 暴露方法
defineExpose({
  getProduce,
});

//无网状态
const connected = () => {
  getappReceive();
};

const del = (item, index) => {
  giftList.value.splice(index, 1);
};
</script>

<template>
  <topNav
    title="新建收货单"
    @search="searchFun"
    @scan="scanFun"
    rType="save"
    :clickable="false"
  ></topNav>

  <view class="goods_top">
    <view class="goods_top-title">{{
      productData.storeCenter && productData.storeCenter.name
    }}</view>
    <up-copy :content="productData.code" class="up-copy">
      <view class="item_title_left">
        <text>单据号：{{ productData.code }}</text>
        <image src="@/static/images/copy.png" mode="scaleToFill" />
      </view>
    </up-copy>
  </view>

  <view class="goods_form">
    <view
      class="scr_item"
      v-for="(item, index) in productData.products"
      :key="index"
      @click="goEdt(item)"
    >
      <view class="item_title" @click.stop>
        <view class="item_img">
          <image :src="item.image" mode="aspectFill" />
        </view>

        <view class="item_title_right">
          <view class="item_title_right-title">
            <text>{{ item.productName }}</text>
          </view>
          <view class="num"
            ><text>x</text>{{ item.orderNum }}{{ item.unit }}
            <text style="margin-left: 10rpx; color: #000"
              >可收数量:{{ item.receiveNumtwo }}</text
            ></view
          >
        </view>
      </view>

      <view class="form_list">
        <view class="form_item">
          <view class="item_left">实际收货<text>*</text> </view>
          <view class="item_right">
            <view class="item_input">
              <up-input
                type="number"
                v-model="item.inReceiveNum"
                placeholder="数量"
                style="font-size: 24rpx"
                border="none"
              >
                <template #prefix>
                  <text class="input_text">x</text>
                </template>

                <template #suffix>
                  <text class="input_text2">{{ item.unit }}</text>
                </template>
              </up-input>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="gift-k">
      <view class="bt_gift">
        <view class="bt_gift-left">赠品</view>
        <view class="add" @click="selectFun">
          <up-icon
            class="plus"
            name="plus"
            :bold="true"
            color="#1679FB"
            size="24rpx"
          ></up-icon>
          <text>增加赠品</text>
        </view>
      </view>
      <view
        class="scr_item scr_item2"
        v-for="(item, index) in giftList"
        :key="index"
        @click="goEdt(item)"
      >
        <view class="item_del" @click.stop="del(item, index)">
          <up-icon
            class="trash"
            name="trash"
            :bold="true"
            color="#fa2626"
            size="38rpx"
          ></up-icon>
        </view>
        <view class="item_title" @click.stop>
          <view class="item_img">
            <view class="item_img_tg">赠品</view>
            <image :src="item.image" mode="aspectFill" />
          </view>

          <view class="item_title_right">
            <view class="item_title_right-title">
              <text>{{ item.name }}</text>
            </view>
            <view class="num"
              ><text>{{ item.categoryName }}</text></view
            >
          </view>
        </view>

        <view class="form_list">
          <view class="form_item">
            <view class="item_left">实际收货<text>*</text> </view>
            <view class="item_right">
              <view class="item_input">
                <up-input
                  type="number"
                  v-model="item.inReceiveNum"
                  placeholder="数量"
                  style="font-size: 24rpx"
                  border="none"
                >
                  <template #prefix>
                    <text class="input_text">x</text>
                  </template>

                  <template #suffix>
                    <text class="input_text2">{{ item.unit }}</text>
                  </template>
                </up-input>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <view class="bt_foods_shs">
      <view class="bt_foods_sh">
        <view class="left"> 签收单据<text>*</text></view>
        <view class="right">
          <up-upload
            @click="getQX"
            :fileList="fileList"
            @afterRead="afterReadTwo"
            @delete="deletePicTwo"
            name="1"
            multiple
            ref="uUpload"
            accept="image"
            :previewFullImage="true"
            :maxCount="6"
            :sizeType="['compressed']"
          ></up-upload>
        </view>
      </view>
      <up-textarea
        v-model="description"
        placeholder="请输入备注"
        count
      ></up-textarea>
    </view>
  </view>

  <view style="width: 100%; height: 100rpx"></view>

  <view class="goods_bt">
    <!-- icon="plus"
    iconColor="#ffffff" -->
    <view class="goods_bt_to"
      ><up-button
        @click="goadd"
        class="goods_bt_to_btn"
        text="确认收货"
      ></up-button>
    </view>
  </view>

  <view class="show-camera" v-if="ishowcamera">
    <view class="show-camera-k">
      <view class="show-sm"> 设备权限使用说明 </view>
      <view class="show-des">
        为了给您带来更好的服务，需要获取您的相机权限与读取图片及文件权限，用于更换上传图片、扫一扫等功能，对于您授权的信息我们竭尽全力提供安全保护。
      </view>
    </view>
  </view>
  <noWork @connected="connected"> </noWork>
</template>

<style lang="scss" scoped>
@import "./index.scss";
</style>
